package com.smartsystem.common.config;

import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.support.http.StatViewServlet;
import com.alibaba.druid.support.http.WebStatFilter;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.sql.DataSource;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

/**
 * Druid数据源配置类
 */
@Configuration
public class DruidConfig {

    /**
     * 配置Druid数据源
     */
    @ConfigurationProperties(prefix = "spring.datasource")
    @Bean
    public DataSource druidDataSource() {
        return new DruidDataSource();
    }

    /**
     * 配置Druid监控页面
     */
    @Bean
    public ServletRegistrationBean<StatViewServlet> statViewServlet() {
        ServletRegistrationBean<StatViewServlet> bean = new ServletRegistrationBean<>(new StatViewServlet(), "/druid/*");
        
        // 配置初始化参数
        Map<String, String> initParams = new HashMap<>();
        // 用户名
        initParams.put("loginUsername", "admin");
        // 密码
        initParams.put("loginPassword", "admin123");
        // 允许访问的IP，为空或者null时，表示允许所有访问
        initParams.put("allow", "");
        // 拒绝访问的IP
        initParams.put("deny", "");
        
        bean.setInitParameters(initParams);
        return bean;
    }

    /**
     * 配置Web监控的Filter
     */
    @Bean
    public FilterRegistrationBean<WebStatFilter> webStatFilter() {
        FilterRegistrationBean<WebStatFilter> bean = new FilterRegistrationBean<>();
        bean.setFilter(new WebStatFilter());
        
        // 配置初始化参数
        Map<String, String> initParams = new HashMap<>();
        // 不统计这些请求数据
        initParams.put("exclusions", "*.js,*.gif,*.jpg,*.png,*.css,*.ico,/druid/*");
        
        bean.setInitParameters(initParams);
        // 设置拦截请求
        bean.setUrlPatterns(Arrays.asList("/*"));
        
        return bean;
    }
}